package xt.outfood.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xt.outfood.common.CustomException;
import xt.outfood.common.Result;
import xt.outfood.dto.SetmealDto;
import xt.outfood.entity.Setmeal;
import xt.outfood.entity.SetmealDish;
import xt.outfood.mapper.SetmealMapper;
import xt.outfood.service.SetmealDishService;
import xt.outfood.service.SetmealService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 此类此时为CategoryService服务
 *
 * @author 小小爱欧
 * @date 2022/7/22 10:46
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDash(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert
        //setmealDto继承了setmeal，可以通过setmealDto直接操作setmeal
        this.save(setmealDto);
        //保存套餐与菜品的关联信息，操作setmeal_dish,执行insert操作
        List<SetmealDish> setmealDishes=setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }


    @Override
    public void removeWithDish(List<Long> ids) {
        //只有停售的才能删除
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        long count = this.count(queryWrapper);
        log.info("this={}",this);
        if (count>0){
            throw new CustomException("套餐正在售卖中，不能删除");

        }
        //如果可以删除，则先删除套餐中的数据--setmeal
        this.removeByIds(ids);
        //再删除关系表中的数据---setmeal_dish
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

    }


}
